/**
 * 真实POI数据获取服务
 * 支持多种数据源：高德地图、百度地图、医院API等
 */

export interface RealPOIData {
  id: string
  name: string
  type: 'department' | 'equipment' | 'entrance' | 'pharmacy' | 'lab' | 'imaging'
  position: [number, number]
  floor?: string
  description?: string
  phone?: string
  address?: string
  openTime?: string
  services?: string[]
  metadata: {
    source: 'amap' | 'baidu' | 'hospital_api' | 'manual'
    category?: string
    distance?: number
    rating?: number
    verified?: boolean
  }
}

export class RealPOIService {
  private amapKey: string
  private baiduKey?: string
  private hospitalApiConfig?: {
    endpoint: string
    apiKey: string
    hospitalId: string
  }

  constructor(config: {
    amapKey: string
    baiduKey?: string
    hospitalApiConfig?: {
      endpoint: string
      apiKey: string
      hospitalId: string
    }
  }) {
    this.amapKey = config.amapKey
    this.baiduKey = config.baiduKey
    this.hospitalApiConfig = config.hospitalApiConfig
  }

  /**
   * 通过高德地图搜索医院POI
   */
  async searchHospitalPOIs(hospitalName: string, city: string = '杭州'): Promise<RealPOIData[]> {
    try {
      const AMap = (window as any).AMap
      if (!AMap) {
        throw new Error('高德地图未加载')
      }

      const poiSearcher = new AMap.PlaceSearch({
        type: '医疗保健服务',
        pageSize: 50,
        pageIndex: 1,
        city: city,
        extensions: 'all'
      })

      return new Promise((resolve, reject) => {
        poiSearcher.search(hospitalName, (status: string, result: any) => {
          if (status === 'complete' && result.info === 'OK') {
            const pois: RealPOIData[] = result.poiList.pois.map((poi: any) => ({
              id: `amap_${poi.id}`,
              name: poi.name,
              type: this.detectPOIType(poi.name),
              position: [poi.location.lng, poi.location.lat],
              floor: 'L1',
              description: poi.address || '',
              phone: poi.tel || '',
              address: poi.address || '',
              services: poi.tag ? poi.tag.split(';') : [],
              metadata: {
                source: 'amap' as const,
                category: poi.type,
                verified: poi.adcode ? true : false
              }
            }))
            resolve(pois)
          } else {
            reject(new Error(`POI搜索失败: ${result.info}`))
          }
        })
      })
    } catch (error) {
      console.error('高德地图POI搜索失败:', error)
      throw error
    }
  }

  /**
   * 搜索指定坐标周边的医疗设施
   */
  async searchNearbyMedicalFacilities(
    center: [number, number], 
    radius: number = 1000
  ): Promise<RealPOIData[]> {
    try {
      const AMap = (window as any).AMap
      if (!AMap) {
        throw new Error('高德地图未加载')
      }

      const nearbySearcher = new AMap.PlaceSearchNearBy({
        type: '医疗保健服务|科教文化服务',
        radius: radius,
        extensions: 'all'
      })

      return new Promise((resolve, reject) => {
        nearbySearcher.searchNearBy('', new AMap.LngLat(center[0], center[1]), radius, (status: string, result: any) => {
          if (status === 'complete' && result.info === 'OK') {
            const pois: RealPOIData[] = result.poiList.pois
              .filter((poi: any) => this.isMedicalRelated(poi.name))
              .map((poi: any) => ({
                id: `nearby_${poi.id}`,
                name: poi.name,
                type: this.detectPOIType(poi.name),
                position: [poi.location.lng, poi.location.lat],
                floor: 'L1',
                description: `距离: ${poi.distance}米`,
                phone: poi.tel || '',
                address: poi.address || '',
                metadata: {
                  source: 'amap' as const,
                  distance: poi.distance,
                  category: poi.type
                }
              }))
            resolve(pois)
          } else {
            reject(new Error(`周边搜索失败: ${result.info}`))
          }
        })
      })
    } catch (error) {
      console.error('周边医疗设施搜索失败:', error)
      throw error
    }
  }

  /**
   * 从医院API获取科室数据
   */
  async getHospitalDepartmentsFromAPI(): Promise<RealPOIData[]> {
    if (!this.hospitalApiConfig) {
      throw new Error('医院API配置未设置')
    }

    try {
      const response = await fetch(`${this.hospitalApiConfig.endpoint}/departments`, {
        headers: {
          'Authorization': `Bearer ${this.hospitalApiConfig.apiKey}`,
          'Content-Type': 'application/json'
        }
      })

      if (!response.ok) {
        throw new Error(`API请求失败: ${response.status}`)
      }

      const data = await response.json()
      
      return data.departments.map((dept: any) => ({
        id: `api_${dept.id}`,
        name: dept.name,
        type: 'department' as const,
        position: [dept.longitude, dept.latitude],
        floor: dept.floor || 'L1',
        description: dept.description || '',
        phone: dept.phone || '',
        address: dept.address || '',
        openTime: dept.openTime || '',
        services: dept.services || [],
        metadata: {
          source: 'hospital_api' as const,
          verified: true,
          category: dept.category
        }
      }))
    } catch (error) {
      console.error('医院API数据获取失败:', error)
      throw error
    }
  }

  /**
   * 批量导入Excel格式的科室数据
   */
  async importFromExcel(file: File): Promise<RealPOIData[]> {
    // 这里可以集成SheetJS或其他Excel解析库
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          // TODO: 实现Excel解析逻辑
          // const workbook = XLSX.read(e.target?.result, { type: 'binary' })
          // const pois = this.parseExcelData(workbook)
          resolve([])
        } catch (error) {
          reject(error)
        }
      }
      reader.readAsBinaryString(file)
    })
  }

  /**
   * 检测POI类型
   */
  private detectPOIType(name: string): RealPOIData['type'] {
    if (name.includes('科') || name.includes('诊')) return 'department'
    if (name.includes('药房') || name.includes('药店')) return 'pharmacy'
    if (name.includes('检验') || name.includes('化验')) return 'lab'
    if (name.includes('影像') || name.includes('CT') || name.includes('MRI')) return 'imaging'
    if (name.includes('入口') || name.includes('大门')) return 'entrance'
    if (name.includes('设备') || name.includes('仪器')) return 'equipment'
    return 'department'
  }

  /**
   * 判断是否为医疗相关POI
   */
  private isMedicalRelated(name: string): boolean {
    const medicalKeywords = [
      '科', '诊', '医', '院', '药', '检验', '化验', 
      '影像', 'CT', 'MRI', '手术', '急诊', '门诊',
      '住院', '病房', '护理', '康复'
    ]
    return medicalKeywords.some(keyword => name.includes(keyword))
  }
}

// 默认实例
export const realPOIService = new RealPOIService({
  amapKey: process.env.NEXT_PUBLIC_AMAP_KEY || '',
  // baiduKey: process.env.NEXT_PUBLIC_BAIDU_KEY,
  // hospitalApiConfig: {
  //   endpoint: process.env.NEXT_PUBLIC_HOSPITAL_API_ENDPOINT || '',
  //   apiKey: process.env.NEXT_PUBLIC_HOSPITAL_API_KEY || '',
  //   hospitalId: process.env.NEXT_PUBLIC_HOSPITAL_ID || ''
  // }
})

export default realPOIService